package com.flca.frw.zk.util;

import java.lang.reflect.Method;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Radio;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Window;

import com.flca.frw.beanutils.MethodHelper;

public class RadioGroupHelper {

	private static Logger logger = LoggerFactory.getLogger(RadioGroupHelper.class);
	
	@SuppressWarnings("unchecked")
	public static void setSelectedItem(Radiogroup aRadioGrp, Object aValue) 
	{
		if (aValue != null) {
			String value = aValue.toString();
			List<Radio> items = aRadioGrp.getChildren();
			for (Radio item : items) {
				if (value.equals(item.getValue()) || value.equals(item.getLabel())) {
					aRadioGrp.setSelectedItem(item);
					return;
				}
			}
		} else {
			aRadioGrp.setSelectedIndex(-1);
		}
	}
	
	public static void updateYesNoRadioGroup(Window aWin, String aFieldname, Object aObject, String aPropertyName, boolean aUpdateView)
	{
		Component comp = aWin.getFellow(aFieldname);
		Radiogroup radioGrp = null;
		if (comp != null && comp instanceof Radiogroup) {
			radioGrp = (Radiogroup) comp;
		}
		try {
			if (aUpdateView) {
				updateYesNoRadioGroupToView(radioGrp, aObject, aPropertyName);
			} else {
				updateYesNoRadioGroupToModel(radioGrp, aObject, aPropertyName);
			}
		} catch (Exception e) {
			String msg = "Error in updateField() comp=" + comp + " obj=" + aObject + 
				" prop=" + aPropertyName + " updateView=" + aUpdateView;
			logger.error(msg, e); 
			e.printStackTrace();
 		}
	}
	
	
	private static void updateYesNoRadioGroupToView(Radiogroup aRadioGrp, Object aObject, String aPropertyName) throws Exception
	{
		Method getter = MethodHelper.getGetter(aObject, aPropertyName);
		if (getter != null) {
			Object value = getter.invoke(aObject, new Object[] {});
			if (value != null && value instanceof Boolean) {
				Boolean b = (Boolean) value;
				if (Boolean.TRUE.equals(b)) { //TODO now always assuming 0 ja 0 nee
					aRadioGrp.setSelectedIndex(0);
				} else if (Boolean.FALSE.equals(b)) {
					aRadioGrp.setSelectedIndex(1);
				} else {
					aRadioGrp.setSelectedIndex(-1);
				}
			} else {
				throw new Exception("no value found for " + aPropertyName);
			}
		} else {
			throw new Exception("no getter found for " + aPropertyName);
		}
	}

	private static void updateYesNoRadioGroupToModel(Radiogroup aRadioGrp, Object aObject, String aPropertyName) throws Exception
	{
		Method setter = MethodHelper.getSetter(aObject, aPropertyName);
		if (setter != null) {
			if (aRadioGrp.getSelectedIndex() == 0) {
				setter.invoke(aObject, new Object[] {Boolean.TRUE});
			} else if (aRadioGrp.getSelectedIndex() == 1) {
				setter.invoke(aObject, new Object[] {Boolean.FALSE});
			} 
		} else {
			throw new Exception("no setter found for " + aPropertyName);
		}
	}
}
